﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Utils;
using System.Collections;
using System.Web.SessionState;
using Utils.Entity;

namespace Utils.DC.Web.UI
{
    /// <summary>
    /// Author: Dao xuan trung
    /// Date: 02/02/2010
    /// Purpose: Cac ham tien ich cho trang web
    /// </summary>
    public class PageUtility
    {
        public static string SESSION_USER_NAME = "CurrentUser";

        #region Lay ve trang hien tai

        /// <summary>
        /// Ham dung de lay ve thong tin cua trang hien tai
        /// </summary>
        /// <param name="Url">
        /// Duong dan url co dang: vitoandolini/san-pham/game.aspx
        /// Check neu chi 1 dau gach (do sau bang 1) thi la function page, ko thi la category page
        /// </param>
        public static PageSettings GetCurrentPage(string Url)
        {
            //Khoi tao 1 bien dung de chua thong tin cua page hien tai

            DataSet ds = new DataSet();
            PageSettings pageSettings = new PageSettings();

            ArrayList partInURL = new ArrayList();
            string subURL = Url.Substring(0, Url.IndexOf(".aspx"));
            string[] str = subURL.Split(new char[] { '/' });
            foreach (string s in str)
            {
                partInURL.Add(s);
            }

            pageSettings.PartInURL = partInURL;

            ds = PageUtility.GetCurrentCategoryPage(Url);
            //set thong tin cua page bang bien table[0]
            try
            {
                DataRow row = ds.Tables[0].Rows[0];
                pageSettings.PageID = Convert.ToInt32(row["FunctionPageID"]);
                pageSettings.PageName = row["FunctionPageName"].ToString().Trim();
                pageSettings.PageAlias = row["FunctionPageAlias"].ToString().Trim();
                pageSettings.PageTitle = row["FunctionPageTitle"].ToString().Trim();
                pageSettings.PageImage = row["FunctionPageImage"].ToString().Trim();
                pageSettings.PageIcon = row["FunctionPageIcon"].ToString().Trim();
                pageSettings.PageContent = row["FunctionPageDescription"].ToString().Trim();
                pageSettings.MetaDescription = row["MetaDescription"].ToString().Trim();
                pageSettings.MetaKeyword = row["MetaKeyword"].ToString().Trim();
                pageSettings.Lang = row["Lang"].ToString().Trim();
                pageSettings.ControlPath = row["ControlPath"].ToString().Trim();
                pageSettings.UrlPath = row["URLPath"].ToString().Trim();
                pageSettings.FunctionType = row["FunctionType"].ToString().Trim();
                pageSettings.IsFunctionPage = false;
                pageSettings.IsAdmin = Convert.ToBoolean(row["IsAdmin"]);
                pageSettings.IsCache = Convert.ToBoolean(row["IsCache"]);
                pageSettings.CacheTime = Convert.ToInt32(row["CacheTime"]);
                pageSettings.HasEntry = Convert.ToBoolean(row["HasEntry"]);
                //Lay ve danh sach nhom quyen duoc su dung trang nay
                DataTable dt2 = ds.Tables[1];
                if (dt2 != null && dt2.Rows.Count > 0)
                {
                    pageSettings.RoleList = new ArrayList();
                    IEnumerator ie = dt2.Rows.GetEnumerator();
                    DataRow dRow = null;
                    PageRoleEntity role = null;
                    while (ie.MoveNext())
                    {
                        role = new PageRoleEntity();
                        dRow = ((DataRow)ie.Current);
                        role.Action = Convert.ToInt32(dRow["Action"]);
                        role.RoleID = Convert.ToInt32(dRow["RoleID"]);
                        role.CategoryPageID = pageSettings.PageID;
                        pageSettings.RoleList.Add(role);
                    }
                }

                //Neu trang nay co entry thi lay ve thong tin cua entry
                int indexCateTable = 0;
                if (pageSettings.HasEntry && ds.Tables[2] != null && ds.Tables[2].Rows.Count > 0)
                {
                    pageSettings.Entry = ds.Tables[2];
                    indexCateTable = 3;
                }
                else
                {
                    indexCateTable = 2;
                }

                //Nếu trang này là trang con thì lấy về thông tin của trang con: abstract, content, ishot, istypical, isnew, parentid
                if (ds.Tables[indexCateTable] != null && ds.Tables[indexCateTable].Rows.Count > 0)
                {
                    pageSettings.PageContent = ds.Tables[indexCateTable].Rows[0]["CategoryPageContent"].ToString().Trim();
                    pageSettings.PageDescription = ds.Tables[indexCateTable].Rows[0]["CategoryPageAbstract"].ToString().Trim();
                    try
                    {
                        pageSettings.ParentID = (int?)Convert.ToInt32(ds.Tables[indexCateTable].Rows[0]["ParentID"]);
                    }
                    catch (Exception e)
                    {
                        pageSettings.ParentID = null;
                    }
                }
            }
            catch (Exception e)
            {
            }
            return pageSettings;
        }

        /// <summary>
        /// Lay ve trang chuc nang hien tai
        /// Author: Dao Xuan Trung
        /// Date: 18/01/2010        
        /// </summary>
        /// <param name="UrlPath">Duong dan dung de check</param>
        /// <returns>Tra ve 1 dataset: table 0: thong tin ve page
        /// </returns>
        public static DataSet GetCurrentFunctionPage(string urlPath)
        {
            try
            {
                return DatabaseUtils.SqlHelper.ExecuteDataset(Common.Conn, "FunctionPage_GetCurrent",urlPath);
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
        }

        /// <summary>
        /// Lay ve trang nhom hien tai
        /// Author: Dao Xuan Trung
        /// Date: 18/01/2010
        /// </summary>
        /// <param name="urlPath">Duong dan dung de check</param>
        /// <returns>Tra ve 1 dataset: table 0: thong tin ve page
        /// </returns>
        public static DataSet GetCurrentCategoryPage(string urlPath)
        {
            try
            {
                return DatabaseUtils.SqlHelper.ExecuteDataset(Common.Conn, "CategoryPage_GetCurrent", urlPath);
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
        }

        
        #endregion

        #region Cac ham thao tac cua nguoi dung

        

        /// <summary>
        /// Dang nhap
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="Password"></param>
        /// <returns></returns>
        public static DataSet Login(String UserName, String Password, String IP)
        {
            try
            {
                return DatabaseUtils.SqlHelper.ExecuteDataset(Common.Conn, "Users_login", UserName, Password, IP);
            }
            catch (Exception e)
            {
                throw new Exception(e.ToString());
            }
        }

        /// <summary>
        /// Ham set session cho user login
        /// </summary>
        /// <param name="session">Session hien tai</param>
        /// <param name="UserInformation">dataset chua thong tin cua user,gom 2 table, table 1 la thong tin user, table 2 la danh sach rolelist</param>
        /// <returns>1: dang nhap thanh cong, 0 la that bai</returns>
        public static byte SetLoginedUser(HttpSessionState session, DataSet UserInformation)
        {
            try
            {
                session.Remove(SESSION_USER_NAME);

                if (UserInformation != null && UserInformation.Tables.Count == 2)
                {
                    session.Add(SESSION_USER_NAME, new UserEntity(UserInformation));
                    return 1;
                }
                return 0;
            }
            catch (Exception e)
            {
                return 0;
            }
        }

        public static byte SetLoginedUser(HttpSessionState session, int userId, string userName)
        {
            try
            {
                session.Remove(SESSION_USER_NAME);

                session.Add(SESSION_USER_NAME, new UserEntity(userId, userName));
                return 1;
            }
            catch (Exception e)
            {
                return 0;
            }
        }

        public static UserEntity IsLogin(HttpSessionState session)
        {
            try
            {
                return (UserEntity)session[SESSION_USER_NAME];
            }
            catch (Exception e)
            {
                return null;
            }
        }

        public static void SighOut(HttpSessionState session)
        {
            try
            {
                session.Remove(SESSION_USER_NAME);
            }
            catch (Exception e)
            {

            }
        }
        #endregion
    }
}
